import 'package:flutter/material.dart';
import 'package:flutter/services.dart'
    show TextInputFormatter, LengthLimitingTextInputFormatter;
import '../src/gkb_app_bar.dart' show GKBBackButton;

class SearchTextFieldBar extends StatefulWidget {
  final String hint;
  final String heroTag;
  final double defaultBorderRadius;
  final EdgeInsets margin;
  final EdgeInsets padding;
  final Color splashColor;
  final TextEditingController textController;
  final FocusNode? focusNode;
  final void Function(String text)? onSubmitted;
  final void Function(String text)? onTextChange;
  final Function()? clearCallback;
  final Function()? onBackCallback;
  final int inputKeyWordsLength;
  final List<TextInputFormatter>? textInputFormatter;
  final double fontSize;
  final Color? color;
  final bool isShowBackButton;
  final double? width;
  final double height;
  final bool autofocus;
  final Color borderBackgroundColor;

  ///搜索图标
  final Widget? searchIcon;

  const SearchTextFieldBar(
      {Key? key,
      required this.hint,
      this.defaultBorderRadius = 20.0,
      required this.textController,
      this.margin = const EdgeInsets.only(top: 10.0, bottom: 10.0),
      this.padding = const EdgeInsets.only(left: 12),
      required this.heroTag,
      this.splashColor = const Color(0xFFB5B5B5),
      this.focusNode,
      this.onSubmitted,
      this.color,
      this.onBackCallback,
      this.clearCallback,
      this.onTextChange,
      this.inputKeyWordsLength = 20,
      this.textInputFormatter,
      this.fontSize = 12,
      this.isShowBackButton = false,
      this.autofocus = true,
      this.borderBackgroundColor = Colors.white,
      this.width,
      this.height = 30,
      this.searchIcon})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return SearchTextFieldBarState();
  }
}

class SearchTextFieldBarState extends State<SearchTextFieldBar> {
  bool showClear = false;
  late FocusNode focusNode;

  late List<TextInputFormatter> formatters;

  // TextEditingController defaultTextController = defaultTextController();

  @override
  void initState() {
    super.initState();
    focusNode = widget.focusNode ?? FocusNode();
    widget.textController.addListener(initListener);
  }

  @override
  void dispose() {
    super.dispose();
    widget.textController.removeListener(initListener);
  }

  void initListener() {
    if (widget.onTextChange != null) {
      widget.onTextChange!(widget.textController.text);
    }
    if (widget.textController.text.isNotEmpty) {
      if (!showClear) {
        showClear = true;
        setState(() {});
      }
    } else {
      if (showClear) {
        showClear = false;
        setState(() {});
      }
    }
  }

  Widget buildHeroWidget(BuildContext context) {
    if (widget.heroTag.isEmpty) {
      return buildHeroContainer();
    } else {
      return Hero(
        tag: widget.heroTag,
        child: buildHeroContainer(),
      );
    }
  }

  Widget buildHeroContainer() {
    return Material(
      color: Colors.transparent,
      child: Container(
        margin: widget.margin,
        child: Row(
          children: [
            buildLeftBackWidget(),
            Expanded(child: buildContentContainer()),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    formatters = <TextInputFormatter>[
      ...?widget.textInputFormatter,
      if (widget.textInputFormatter == null)
        LengthLimitingTextInputFormatter(
          widget.inputKeyWordsLength,
        ),
    ];
    return buildHeroWidget(context);
  }

  Widget buildLeftBackWidget() {
    if (widget.isShowBackButton) {
      return GKBBackButton(
        onTap: () {
          if (widget.onBackCallback != null) {
            widget.onBackCallback!();
          } else {
            Navigator.of(context).pop();
          }
        },
      );
    }
    return Container();
  }

  Container buildContentContainer() {
    return Container(
      height: widget.height,
      // width: double.infinity,
      alignment: const Alignment(-1, 0),
      padding: widget.padding,
      decoration: BoxDecoration(
        color: widget.borderBackgroundColor,
        borderRadius: BorderRadius.circular(widget.defaultBorderRadius),
      ),
      child: buildRow(),
    );
  }

  double calculateWidth() {
    if (widget.width != null) {
      return widget.width!;
    }
    double width = 200;
    if (widget.isShowBackButton) {
      width -= 60;
    }
    return width;
  }

  Row buildRow() {
    const String searchCommon = 'assets/images/search_common.png';

    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        widget.searchIcon ??
            Image.asset(
              searchCommon,
              width: 16.0,
              height: 16.0,
            ),
        const SizedBox(
          width: 5.0,
        ),
        Expanded(
          flex: 1,
          child: Container(
            alignment: const Alignment(-1, 0),
            child: buildTextField(),
          ),
        ),
        buildClearButton(),
      ],
    );
  }

  TextField buildTextField() {
    return TextField(
      keyboardType: TextInputType.text,
      textInputAction: TextInputAction.search,

      ///只有苹果手机上有效果
      keyboardAppearance: Brightness.dark,
      controller: widget.textController,
      maxLines: 1,
      inputFormatters: formatters,
      onSubmitted: (text) {
        if (widget.onSubmitted != null) {
          widget.onSubmitted!(text);
        }
      },
      autofocus: widget.autofocus,
      focusNode: widget.focusNode,
      style: TextStyle(
          fontSize: widget.fontSize,
          color: widget.color ?? Colors.black,
          fontWeight: FontWeight.w300),
      decoration: InputDecoration(
          isDense: true,
          contentPadding: EdgeInsets.zero,
          border: InputBorder.none,
          hintText: widget.hint,
          hintStyle: TextStyle(
            fontSize: widget.fontSize,
            color: const Color(0xffb5b5b5),
          )),
    );
  }

  buildClearButton() {
    if (showClear) {
      return IconButton(
        icon: const Icon(
          Icons.cancel,
          size: 12,
          color: Color(0xffcecece),
        ),
        onPressed: () {
          showClear = false;
          setState(() {});
          widget.textController.text = "";
          if (widget.clearCallback != null) {
            widget.clearCallback!();
          }
        },
      );
    } else {
      return Container();
    }
  }
}
